import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Start {

	private static Browser browserWidget;
	private static StyledText textWidget;
	private static File xmlFile;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setText("Hello world!");
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		shell.setLayout(gridLayout);
		browserWidget = new Browser(shell, SWT.NONE);
		GridUtils.fillBoth(browserWidget);
		textWidget = new StyledText(shell, SWT.NONE);
		GridUtils.fillBoth(textWidget);
		Button button = new Button(shell, SWT.NONE);
		button.setText("Display");
		GridUtils.fillHorz(button);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				File xmlFile = getXmlFile();
				if (xmlFile != null) {
					browserWidget.setUrl(xmlFile.getPath());
				}
			}
		});
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}

	private static File getXmlFile() {
		BufferedWriter xmlWriter = null;
		try {
			if (xmlFile != null) {
				xmlFile.delete();
			}
			xmlFile = File.createTempFile("ttttemp", ".xml");
			System.err.println(xmlFile.getAbsolutePath());
			xmlWriter = new BufferedWriter(new FileWriter(xmlFile));
			String xml = textWidget.getText();
			xmlWriter.write(xml);
			xmlWriter.flush();
			return xmlFile;
		} catch (IOException e) {
		} finally {
			try {
				xmlWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}